package com.lcu.wl.modules.sys.service.impl;

import com.lcu.wl.common.utils.SYSDATA;
import com.lcu.wl.common.utils.TokenGenerator;
import com.lcu.wl.modules.sys.entity.UserToken;
import com.lcu.wl.modules.sys.mapper.UserTokenMapper;
import com.lcu.wl.modules.sys.service.IUserTokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 系统用户Token 服务实现类
 * </p>
 *
 * @author wanglei
 * @since 2021-01-14
 */
@Service("userTokenService")
public class UserTokenServiceImpl extends ServiceImpl<UserTokenMapper, UserToken> implements IUserTokenService {

    //12小时 token有效时间
    private final static int EXPIRE = 3600 * 12;

    @Override
    public SYSDATA createToken(Long userId) {
        //生成token
        String token = TokenGenerator.generateValue();

        Date now = new Date();
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判读是否有token
        UserToken userToken = this.getById(userId);
        if (userToken == null){
            userToken = new UserToken();
            userToken.setUserId(userId);
            userToken.setToken(token);
            userToken.setUpdateTime(now);
            userToken.setExpireTime(expireTime);
            //保存token
            this.save(userToken);
        }else{
            userToken.setToken(token);
            userToken.setUpdateTime(now);
            userToken.setExpireTime(expireTime);
            //更新token
            this.updateById(userToken);
        }
        SYSDATA sysdata = SYSDATA.ok().put("token",token).put("expire",EXPIRE);
        return sysdata;
    }

    @Override
    public void logout(Long userId) {
        //生成token
        String token = TokenGenerator.generateValue();
        //修改token
        UserToken userToken = new UserToken();
        userToken.setUserId(userId);
        userToken.setToken(token);
        this.updateById(userToken);
    }
}
